package com.sphd.emanu.activity.storagemanage;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.github.yoojia.inputs.AndroidNextInputs;
import com.github.yoojia.inputs.Scheme;
import com.github.yoojia.inputs.StaticScheme;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.sphd.emanu.R;
import com.sphd.emanu.adapter.StorageManageAdapter;
import com.sphd.emanu.config.Constant;
import com.sphd.emanu.mvp.MVPBaseActivity;
import com.sphd.emanu.permission.Moudle;
import com.sphd.emanu.pojo.login.User;
import com.sphd.emanu.pojo.material.Material;
import com.sphd.emanu.pojo.material.Storage;
import com.sphd.emanu.utils.PermissionConfig;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * TODO 库位管理
 *
 * @Author Hu
 * @Time 2017/6/2 -- 14:37.
 * @Email 87683202@qq.com
 */
public class StorageManageActivity extends MVPBaseActivity<StorageManageContract.View, StorageManagePresenter> implements StorageManageContract.View {

    @BindView(R.id.btn_add_storage)
    TextView btnAddStorage;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.my_recycler)
    RecyclerView myRecycler;
    @BindView(R.id.my_swf)
    SwipeRefreshLayout mySwf;
    Intent intent;
    Bundle bundle;
    User user;
    StorageManageAdapter storageManageAdapter;
    AndroidNextInputs inputs;
    View view;
    MaterialEditText mNo, mName, mAllName, mVol;
    TextView title;
    Button btnSave;
    AlertDialog alertDialog;
    int itemId = 0;//通过对id是不是等于0进行判断，从而进行区分是新增还是修改
    List<Moudle> moudles;
    boolean isCanDo = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_storage_manage);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        mySwf.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                addData();
            }
        });
        myRecycler.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                Storage storage = (Storage) adapter.getItem(position);
                title.setText("库位详情");
                mNo.setText(String.valueOf(storage.getSn()));
                mName.setText(storage.getName());
                mAllName.setText(storage.getFullName());
                mVol.setText(String.valueOf(storage.getVolume()));
                btnSave.setVisibility(View.INVISIBLE);
                mNo.setEnabled(false);
                mName.setEnabled(false);
                mAllName.setEnabled(false);
                mVol.setEnabled(false);
                if (alertDialog != null) {
                    if (!alertDialog.isShowing())
                        alertDialog.show();
                }
            }

            @Override
            public void onItemLongClick(final BaseQuickAdapter adapter, View view, final int position) {
                super.onItemLongClick(adapter, view, position);
                if (isCanDo)
                    new SweetAlertDialog(context, SweetAlertDialog.WARNING_TYPE).setTitleText("确定要删除吗？")
                            .setConfirmText("确定").setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            showProgressDialog();
                            mPresenter.deleteStorage(((Storage) adapter.getItem(position)).getId(), position, sweetAlertDialog);
                        }
                    }).setCancelText("取消").setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                        }
                    }).show();

            }

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemChildClick(adapter, view, position);
                Storage storage = (Storage) adapter.getItem(position);
                title.setText("编辑库位");
                mNo.setText(String.valueOf(storage.getSn()));
                mName.setText(storage.getName());
                mAllName.setText(storage.getFullName());
                mVol.setText(String.valueOf(storage.getVolume()));
                btnSave.setVisibility(View.VISIBLE);
                mNo.setEnabled(true);
                mName.setEnabled(true);
                mAllName.setEnabled(true);
                mVol.setEnabled(true);
                if (alertDialog != null) {
                    if (!alertDialog.isShowing())
                        alertDialog.show();
                    itemId = storage.getId();
                }
            }
        });
    }

    private void initView() {
        setTitleBar(toolbar, "库位管理");
        inputs = new AndroidNextInputs();
        intent = getIntent();
        bundle = intent.getExtras();
        user = (User) intent.getSerializableExtra(Constant.USER_ENTITY);
        moudles = (List<Moudle>) bundle.getSerializable(Constant.PERMISSION_LIST);
        isCanDo = isCanDo(moudles, PermissionConfig.MENU_STOREHOUSE_8);
        if (!isCanDo) {
            btnAddStorage.setVisibility(View.GONE);
        }
        initDialogView();
        iniAdapter();
        setRefresh(mySwf);
        addData();
    }

    private void initDialogView() {
        view = View.inflate(context, R.layout.dialog_add_edit_storage, null);
        alertDialog = getDialogBuilder(view, R.style.AlertDialog);
        title = (TextView) view.findViewById(R.id.title);
        mNo = (MaterialEditText) view.findViewById(R.id.m_no);
        mName = (MaterialEditText) view.findViewById(R.id.m_name);
        mAllName = (MaterialEditText) view.findViewById(R.id.m_all_name);
        mVol = (MaterialEditText) view.findViewById(R.id.m_volume);
        inputs.add(mNo, StaticScheme.NotBlank().msgOnFail("编号不能为空"));
        inputs.add(mName, StaticScheme.NotBlank().msgOnFail("名称不能为空"));
        inputs.add(mAllName, StaticScheme.NotBlank().msgOnFail("全称不能为空"));
        inputs.add(mVol, StaticScheme.NotBlank().msgOnFail("容量不能为空"));
        btnSave = (Button) view.findViewById(R.id.btn_save);
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (inputs.test()) {
                    if (itemId == 0) {
                        mPresenter.addStorage(Integer.valueOf(mNo.getText().toString().trim()), mName.getText().toString().trim(), mAllName.getText().toString().trim()
                                , Long.valueOf(mVol.getText().toString().trim()), user.getOid());
                    } else {
                        mPresenter.updateStorage(itemId, Integer.valueOf(mNo.getText().toString().trim()), mName.getText().toString().trim(), mAllName.getText().toString().trim()
                                , Long.valueOf(mVol.getText().toString().trim()), user.getOid());
                    }
                } else {
                    toast("请安要求填写");
                }
            }
        });

    }

    private void iniAdapter() {
        setRecy(myRecycler);
        storageManageAdapter = new StorageManageAdapter(R.layout.item_storage_manage, new ArrayList<Storage>(), isCanDo);
        storageManageAdapter.setEmptyView(emptyView);
        myRecycler.setAdapter(storageManageAdapter);
    }

    private void addData() {
        showProgressDialog();
        mPresenter.selectStorage(user.getOid());
    }

    @Override
    public void setAddUpRes(int res) {
        if (res == 1) {
            toast("操作成功");
            addData();
            alertDialog.dismiss();
        } else {
            toast("操作失败，请重试。");
        }
    }

    @Override
    public void setDelRes(int res, Integer pos, SweetAlertDialog sweetAlertDialog) {
        dissProgressDialog();
        if (res == 1) {
            toast("删除成功");
            storageManageAdapter.remove(pos);
            sweetAlertDialog.dismiss();
        } else {
            toast("删除失败，请重试。");
        }
    }

    @Override
    public void setStorageList(List<Storage> storageList) {
        dissProgressDialog();
        storageManageAdapter.setNewData(storageList);
    }

    @OnClick(R.id.btn_add_storage)
    public void onViewClicked() {
        title.setText("新增库位");
        mNo.setEnabled(true);
        mName.setEnabled(true);
        mAllName.setEnabled(true);
        mVol.setEnabled(true);
        mNo.setText(null);
        mName.setText(null);
        mAllName.setText(null);
        mVol.setText(null);
        if (alertDialog != null) {
            if (!alertDialog.isShowing())
                alertDialog.show();
            itemId = 0;
        }


    }
}
